package com.technology.education.ui.student.course

import android.os.Bundle
import android.view.Gravity
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.angcyo.dsladapter.*
import com.technology.education.R
import com.technology.education.data.model.CollectCourse
import com.technology.education.data.model.CourseCategory
import com.technology.education.dslitem.AppStatusItem
import com.technology.education.dslitem.ItemSingleText
import com.technology.education.ext.checkLogin
import com.technology.education.ext.getColor
import com.technology.education.ext.loadImage
import com.technology.education.ext.setPageItems
import com.technology.education.ui.student.course_detail.CourseDetailActivity
import com.technology.education.widget.MyRecylcerView
import me.hgj.jetpackmvvm.base.fragment.BaseVmFragment
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.util.startActivity

/**
 *@author:create by BZY
 *Date: 2022/3/11 10
 */
class CourseListFragment : BaseVmFragment<CourseListViewModel>() {

    companion object {
        fun newInstance(type: ArrayList<CourseCategory>): Fragment {
            val args = Bundle()
            args.putParcelableArrayList("type", type)
            val fragment = CourseListFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun layoutId(): Int = R.layout.fragment_course_list

    var rightAdapter: DslAdapter = DslAdapter().apply {
        dslAdapterStatusItem = AppStatusItem()
        dslLoadMoreItem.onLoadMore = {
            mViewModel.loadMore()
        }
    }
    var leftAdapter: DslAdapter = DslAdapter()

    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.categoryList = arguments?.getParcelableArrayList("type")
        initRecy()
    }

    private fun initRecy() {
        view?.findViewById<MyRecylcerView>(R.id.rv_left)?.apply {
            adapter = leftAdapter
            layoutManager = LinearLayoutManager(requireContext())
            addItemDecoration(DslItemDecoration())
            setHasFixedSize(true)
        }
        view?.findViewById<MyRecylcerView>(R.id.rv_right)?.apply {
            adapter = rightAdapter
            setHasFixedSize(true)
            addItemDecoration(DslItemDecoration())
            layoutManager = GridLayoutManager(requireContext(), 2).apply {
                spanSizeLookup = dslSpanSizeLookup(rightAdapter)
            }
        }

    }

    override fun lazyLoadData() {
        setCategory()
        rightAdapter.updateAdapterStatus(DslAdapterStatusItem.ADAPTER_STATUS_LOADING)
        mViewModel.getData()
    }

    private fun setCategory() {
        leftAdapter.render {
            mViewModel.categoryList?.let {
                mViewModel.selectCategory = it[0].id
                updateTitle(it[0].name)
                resetItem(it.toDslItemList(R.layout.item_single_text) {
                    itemBindOverride = { itemHolder, _, _, _ ->
                        itemBottomInsert = 1 * dpi
                        itemDecorationColor = getColor(R.color.line)
                        itemData?.let { data ->
                            if (data is CourseCategory) {
                                itemHolder.tv(R.id.tv_title)?.text = data.name
                                itemTag = data.id
                                itemHolder.v<LinearLayout>(R.id.ll_parent)?.apply {
                                    setBackgroundColor(getColor(if (mViewModel.selectCategory == data.id) R.color.bg_activity_gray else R.color.white))
                                }
                                itemHolder.clickItem {
                                    if (mViewModel.selectCategory != data.id) {
                                        mViewModel.selectCategory = data.id
                                        updateAllItem()
                                        mViewModel.refresh()
                                        updateTitle(data.name)
                                    }
                                }
                            }
                        }
                    }
                })
            }
        }
    }

    private fun updateTitle(name: String) {
        rightAdapter.render {
            updateOrInsertHeaderItem<DslAdapterItem>(
                "header",
                0
            ) { it ->
                it.apply {
                    itemLayoutId = R.layout.item_single_text
                    itemSpanCount = -1
                    itemLeftInsert = 12 * dpi
                    itemBindOverride = { itemHolder, _, _, _ ->
                        itemHolder.tv(R.id.tv_title)?.apply {
                            gravity = Gravity.LEFT and Gravity.CENTER_VERTICAL
                            textSize = 18f
                            text = name
                            paint.isFakeBoldText = true
                        }
                    }
                }
            }
        }
    }

    override fun createObserver() {
        mViewModel.result.observe(this) {
            parseState(it, onSuccess = { data ->
                rightAdapter.setLoadMoreEnable(data.total > mViewModel.pageIndex * mViewModel.pageSize)
                setUI(data.list ?: listOf())
            }, onError = {
                rightAdapter.updateAdapterStatus(DslAdapterStatusItem.ADAPTER_STATUS_ERROR)
            })
        }
    }

    private fun setUI(list: List<CollectCourse>) {
        rightAdapter.render {
            rightAdapter.updateAdapterStatus(DslAdapterStatusItem.ADAPTER_STATUS_NONE)
            setPageItems(list.toDslItemList(R.layout.item_course_category) {
                itemBottomInsert = 18 * dpi
                itemBindOverride = { itemHolder, _, _, _ ->
                    itemData?.let {
                        if (it is CollectCourse) {
                            itemHolder.tv(R.id.tv_name)?.text = it.name
                            itemHolder.v<ImageView>(R.id.iv_cover)?.apply {
                                loadImage(it.image, this)
                            }
                            itemHolder.clickItem { _ ->
                                if (checkLogin()) {
                                    this@CourseListFragment.startActivity(
                                        CourseDetailActivity::class, Pair("id", it.id),
                                        Pair("title", it.name),
                                        Pair("url", it.url ?: "")
                                    )
                                }
                            }
                        }
                    }

                }
            }, mViewModel.pageIndex)
        }
    }

    override fun showLoading(message: String) {
    }

    override fun dismissLoading() {
    }
}